<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="小程序名称" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 分类管理table -->
    <el-table stripe :data="dataTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" prop="admin_name" label="归属" min-width="110" align="center" fixed></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="200" align="center" prop="platter_id" label="分发批次" fixed>
        <template slot-scope="scope">
          <el-select v-show="scope.row.batchArr.length>0" v-model="scope.row.batchArr" placeholder="请选择" multiple disabled>
            <el-option
              v-for="item in scope.row.batchNameArr"
              :key="item.id"
              :label="item.batch"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" label="logo" min-width="150" align="center" fixed>
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.logo" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="domain" label="版权信息" min-width="150" align="center" fixed></el-table-column>
      <el-table-column v-if="colData[4].istrue" prop="name" label="家长端小程序名称" min-width="200"  align="center"></el-table-column>
      <el-table-column v-if="colData[5].istrue" label="家长端小程序二维码" min-width="200" align="center" >
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.qrcode_img" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" label="家长端小程序背景" min-width="200" align="center">
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.parent_bg" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" prop="after_sale_name" label="售后小程序名称" min-width="200"  align="center"></el-table-column>
      <el-table-column v-if="colData[8].istrue" label="售后小程序二维码" min-width="180" align="center">
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.after_sale_qrcode" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[9].istrue" label="售后小程序背景" min-width="180"  align="center">
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.after_sale_bg" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[10].istrue"  prop="create_time" label="创建时间" min-width="140" align="center">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getMiniInfoById(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getdeleteCategory(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" :page-sizes="[10, 50, 100, 200]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 隐藏 -->
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog :title="editSubjects ? '添加' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="45%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules">
          <el-form-item label="SN码批次:" label-width="130px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="没有选中任何项" multiple filterable class="add_select">
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="logo图片:" label-width="130px" prop="logo">
            <el-upload
              class="avatar-uploader"
              action
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="logoImgUpload"
            >
              <img v-if="addForm.logo" :src="addForm.logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="版权:" label-width="130px" prop="domain">
            <el-input v-model="addForm.domain"  placeholder="请输入版权提示企业信息" :maxlength="30" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="家长端小程序名称:" label-width="130px" prop="name">
            <el-input v-model="addForm.name"  placeholder="请输入家长端微信小程序名" :maxlength="30" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="二维码图片:" label-width="130px" prop="qrcode_img">
            <el-upload
              class="avatar-uploader"
              action
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="qrCodeImgUpload"
            >
              <img v-if="addForm.qrcode_img" :src="addForm.qrcode_img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="小程序背景图:" label-width="130px" prop="parent_bg">
            <el-upload
              class="avatar-uploader"
              action
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="parentBgUpload"
            >
              <img v-if="addForm.parent_bg" :src="addForm.parent_bg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="售后小程序名称:" label-width="130px" prop="after_sale_name">
            <el-input v-model="addForm.after_sale_name"  placeholder="请输入售后微信小程序名" :maxlength="30" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="二维码图片:" label-width="130px" prop="after_sale_qrcode">
            <el-upload
              class="avatar-uploader"
              action
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="afterSaleQrCoddUpload"
            >
              <img v-if="addForm.after_sale_qrcode" :src="addForm.after_sale_qrcode" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="小程序背景图:" label-width="130px" prop="after_sale_bg">
            <el-upload
              class="avatar-uploader"
              action
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="afterSaleBgUpload"
            >
              <img v-if="addForm.after_sale_bg" :src="addForm.after_sale_bg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="toAddMiniProgramInfo('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click="toEditMiniProgramInfo('ruleForm')" size="mini" round>编辑</el-button>
        </div>
      </el-dialog>
      <!-- 删除弹窗 -->
      <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
    </div>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable/index";
import objectable from "@/utils/objectable.js";
import {
  uploadPreviewImg,
  addMiniProgramInfo,
  queryMiniProgramInfo, queryMiniInfoById, editMiniProgramInfo, delMiniProgramInfo
} from "@/api/application";
import deleteDialog from "@/components/deleteDialog/index";
import { getBatchTwo } from "@/api/equipment.js";
import {ossImage} from "@/utils/ossUpload";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "分发批次", "logo", "版权信息", "家长端微信小程序名称", "家长端小程序二维码", "家长端小程序背景", "售后小程序名称", "售后小程序二维码", "售后小程序背景", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      dataTable: [],
      select: "", //搜索条件
      searchTable: "",
      total: 0, //总数量
      //添加表单
      addForm: {
        name: "",
        qrcode_img: "",
        batch: '',
        logo: "",
        domain: "",
        after_sale_name: "",
        parent_bg: "",
        after_sale_qrcode: "",
        after_sale_bg: ""
      },
      //批次下拉选择
      lotoptions: [],
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //编辑专题id
      subjectId: 0,
      rules: {
        batch: [{ required: true, message: "请选择分发批次", trigger: "blur" }],
      },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, name: undefined, },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 }
    };
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryMiniInfo()
  },
  methods: {
    //删除
    getdeleteCategory(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      delMiniProgramInfo(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryMiniInfo()
      }).catch(err => { })
    },
    getqueryMiniInfo() {
      queryMiniProgramInfo(this.listQuery).then(res => {
        this.dataTable = res.data
        this.total = res.total
      }).catch(err => {
        //this.$message.error(err.msg)
        this.dataTable = []
        this.total = 0
      })
    },
    //应用图标上传时的钩子
    iconAvatarSuccess(res, file) {
      let fd = new FormData();
      fd.append('file', res.raw);
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('userId', localStorage.getItem("ID"))
      uploadPreviewImg(fd).then(res => {
        this.addForm.img = res.data.imgPath
        console.log('图片上传', this.addForm.img)
      }).catch(err => {
        console.log("请求失败22", err);
      })
    },
    //分页
    handleSizeChange(val) {
      //console.log("每页多少天", val);
      this.listQuery.pageSize = val
      this.getqueryMiniInfo();
    },
    handleCurrentChange(val) {
      //console.log("当前多少也", val);
      this.listQuery.startSize = val
      this.getqueryMiniInfo();
    },
    Refresh() {
      this.listQuery = {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 1,
        name: undefined,
      }
      this.getqueryMiniInfo()
    },
    btnaddBrand() {
      this.getBatchTwos()
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    toAddMiniProgramInfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addMiniProgramInfo(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryMiniInfo()
            this.dialogFormVisible = false
          }).catch(err => {
            this.getqueryMiniInfo()
            this.dialogFormVisible = false
          })
        } else {
          return false;
        }
      });
    },
    //编辑应用分类
    toEditMiniProgramInfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.id = this.subjectId
          editMiniProgramInfo(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryMiniInfo()
            this.dialogFormVisible = false
          }).catch(err => {
            console.log("请求失败222", err);
          })
        } else {
          return false
        }
      })
    },
    //根据ID查找应用分类信息
    getMiniInfoById(id) {
      this.editSubjects = false
      this.subjectId = id
      this.getBatchTwos()
      queryMiniInfoById({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        this.addForm.name = data.name
        this.addForm.qrcode_img = data.qrcode_img
        this.addForm.logo = data.logo
        this.addForm.domain = data.domain
        this.addForm.batch = data.batch.split(',')
        this.addForm.parent_bg = data.parent_bg
        this.addForm.after_sale_qrcode = data.after_sale_qrcode
        this.addForm.after_sale_name = data.after_sale_name
        this.addForm.after_sale_bg = data.after_sale_bg
      }).catch(err => {
        console.log("请求失败222", err);
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //图片上传
    qrCodeImgUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.addForm.qrcode_img = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },
    logoImgUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.addForm.logo = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },
    parentBgUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.addForm.parent_bg = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },
    afterSaleQrCoddUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.addForm.after_sale_qrcode = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },
    afterSaleBgUpload(res, file) {
      ossImage(res.raw,res.name).then(res => {//图片上传
        this.addForm.after_sale_bg = res
      }).catch(err => {
        this.$message.error("图标上传失败")
      })
    },

    //搜索,1，专题名称
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.name = this.searchTable
          this.getqueryMiniInfo();
          break;
      }
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
      })
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
